package com.google.qam.texture;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;

public final class DrawableTexture extends Texture {
	private static final HashMap<String, SoftReference<DrawableTexture>> cache = new HashMap<String, SoftReference<DrawableTexture>>();
	
	private final String mValue;
	private Drawable mDrawable;
	private Rect mPadding;
	
	public static DrawableTexture createDrawableTexture(String uniqueValue) {
		DrawableTexture texture = null;
		
		final SoftReference<DrawableTexture> reference = cache.get(uniqueValue);
		if(reference != null) {
			texture = reference.get();
		}
		
		if(texture == null) {
			texture = new DrawableTexture(uniqueValue);
			if(cache.containsKey(uniqueValue)) cache.remove(uniqueValue);
			cache.put(uniqueValue, new SoftReference<DrawableTexture>(texture));
		}
		
		return texture;
	}
	
	private DrawableTexture(String value) {
		mValue = value;
	}

	public DrawableTexture setPadding(Rect padding) {
		if(!padding.equals(mPadding)) {
			mState = STATE_UNLOADED;
			mPadding = padding;
		}
		
		return this;
	}
	
	public DrawableTexture setPadding(int left, int top, int right, int bottom) {
		return setPadding(new Rect(left, top, right, bottom));
	}
	
	public Drawable loadColor() {
		if(mState == STATE_UNLOADED) {
			mState = STATE_LOADED;
			try {
				mDrawable = new ColorDrawable(Integer.parseInt(mValue));
				if(mPadding != null)
					mDrawable.setBounds(mPadding);
			} catch(NumberFormatException e) {
				throw new RuntimeException(e); 
			}
		}
		
		return mDrawable;
	}
	
	public Drawable loadNinePatch(Context context) {
		if(mState == STATE_UNLOADED) {
			mState = STATE_LOADED;
			if(mPadding == null) {
				mPadding = new Rect();
			}
			try {
				Bitmap b = ResourceTexture.createResourceTexture(Integer.parseInt(mValue))
					.load(context);
				mDrawable = new NinePatchDrawable(context.getResources(), 
						  b, b.getNinePatchChunk(), 
						  mPadding, null);
			} catch(NumberFormatException e) {
				throw new RuntimeException(e);
			}
		}
		
		return mDrawable;
	}
	
	@Override
	public Bitmap load(Context context) {
		if(!isLoaded()) {
			throw new RuntimeException("Drawable must have been loaded at least once");
		}
		
		return ((BitmapDrawable)mDrawable).getBitmap();
	}
}
